import os

#Generate dkms.conf
dmks_conf = "PACKAGE_NAME=\"drivers_Wupper\"\n"
dmks_conf += "PACKAGE_VERSION=\"" + str(os.environ['RELEASE_TAG']) + "\"\n"

dmks_conf_append = """
REMAKE_INITRD="no"

BUILT_MODULE_NAME[0]="wupper"
BUILT_MODULE_LOCATION[0]="drivers"
DEST_MODULE_LOCATION[0]="/extra"
MAKE[0]='make -C src'

BUILT_MODULE_NAME[1]="cmem_rcc"
BUILT_MODULE_LOCATION[1]="drivers"
DEST_MODULE_LOCATION[1]="/extra"
MAKE[1]='make -C src'

AUTOINSTALL="yes"
CLEAN='make clean -C src'
"""

dmks_conf += dmks_conf_append

with open('dkms.conf', 'w') as f:
  f.write(dmks_conf)


#Generate RPM makefile
makefile = """KERNEL_VERSION := $(shell uname -r)
KERNEL_MODLIB  := /lib/modules/$(KERNEL_VERSION)
KERNEL_SOURCES := $(shell test -d $(KERNEL_MODLIB)/source && echo $(KERNEL_MODLIB)/source || echo $(KERNEL_MODLIB)/build)

CPPFLAGS      += -I$(PWD)/../wupper -I$(PWD)/.. -DBUILD_64_BIT -DCOMPILE_DRIVER -DDRIVER_ERROR -DDRIVER_DEBUG -DRELEASE_NAME=\\"${RELEASE_NAME}\\" -DCVSTAG=\\"$(CVSTAG)\\"
EXTRA_CFLAGS  := -I$(PWD)/../wupper -I$(PWD)/.. -DBUILD_64_BIT -DCOMPILE_DRIVER -DDRIVER_ERROR -DDRIVER_DEBUG -DRELEASE_NAME=\\"${RELEASE_NAME}\\" -DCVSTAG=\\"$(CVSTAG)\\" -DCMEM_RCC_TAG=\\"$(CMEM_RCC_TAG)\\" -DWUPPER_TAG=\\"$(WUPPER_TAG)\\" 

"""

makefile += "RELEASE_NAME := \"" + os.environ['RELEASE_NAME'] + "\" \n"
makefile += "CVSTAG := \"" + os.environ['GIT_BUILD_HASH'] + "\" \n"
makefile += "WUPPER_TAG := \"" + os.environ['GIT_BUILD_HASH'] + "\" \n"
makefile += "CMEM_RCC_TAG := \"" + os.environ['GIT_BUILD_HASH'] + "\" \n"

makefile += """

obj-m   := cmem_rcc.o wupper.o
KDIR  := $(KERNEL_SOURCES)
PWD := $(shell pwd)
default:
\t$(MAKE) -C $(KDIR) M=$(PWD) RELEASE_NAME="\\"$(RELEASE_NAME)\\"" CVSTAG="\\"$(CVSTAG)\\"" WUPPER_TAG="\\"$(WUPPER_TAG)\\"" CMEM_RCC_TAG="\\"$(CMEM_RCC_TAG)\\"" modules
\tmkdir -p ../drivers 
\tmv cmem_rcc.ko ../drivers/
\tmv wupper.ko ../drivers/
clean:
\t$(RM) cmem_rcc.ko.unsigned cmem_rcc.mod.c cmem_rcc.mod.o cmem_rcc.o modules.order Module.symvers .cmem_rcc* .tmp_versions/*
"""

with open('Makefile_drivers', 'w') as m:
  m.write(makefile)

